package cn.net.mugui.net.p2p;

import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.function.BiConsumer;

import com.alibaba.fastjson.JSONArray;
import com.mugui.base.base.Autowired;
import com.mugui.base.base.Component;
import com.mugui.base.client.net.base.Manager;
import com.mugui.sql.util.StringUtils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.Setting;
import cn.hutool.setting.SettingUtil;
import cn.net.mugui.net.conf.SysConf;
import cn.net.mugui.net.dao.Dao;
import cn.net.mugui.net.task.PerHandleTask;
import cn.net.mugui.net.task.WaitConnectionTask;
import cn.net.mugui.net.udp.UdpServer;
import cn.net.mugui.net.udp.UdpServerManager;

/**
 * p2p的连接管理器
 *
 * @author 木鬼
 */
@Component
public class ServerManager extends Manager<String, ServerAttr> {

	@Autowired
	private UdpBagHandle udpBagHandle;

	@Autowired
	private Dao dao;

	@Autowired
	private SysConf conf;
	@Autowired
	private WaitConnectionTask WaitConnectionTask;
	@Autowired
	private UdpServerManager udpServerManager;

	@Override
	public boolean init(Object object) {
		if (isInit())
			return false;
		boolean init = super.init(object);
		UdpServer.setDefaultReceiveListener(udpBagHandle);
		dao.createTable(ServerAttr.class);
		List<ServerAttr> selectList = dao.selectList(new ServerAttr());
		selectList.forEach(t -> {
			if (t.getType() == ServerAttr.type_1) {
				t.setStatus(ServerAttr.status_1);
			}
			System.out.println(t);
			if (StrUtil.isBlank(t.getAddress())) {
				dao.remove(t);
			} else
				add(t.getAddress(), t);
		});
		try {
			// 加载默认公网服务器
			Setting setting = SettingUtil.get("公网服务器配置.txt");
			ServerAttr serverAttr = new ServerAttr();
			setting.forEach(new BiConsumer() {
				@Override
				public void accept(Object t, Object u) {
					serverAttr.set(t.toString(), u);
				}
			});
			if (StringUtils.isBlank(serverAttr.getHost()) || serverAttr.getPort() <= 0) {
				return init;
			}
			serverAttr.setStatus(ServerAttr.status_1);
			serverAttr.setType(ServerAttr.type_1);
			if (StringUtils.isBlank(serverAttr.getName())) {
				serverAttr.setName("默认");
			}
			if (StringUtils.isBlank(serverAttr.getAddress())) {
				serverAttr.setName("TU8yDTWmNg69CUS6PesMPvUL1YwEs2K8uW");
			}
			if (get(serverAttr.getAddress()) == null) {
				add(serverAttr.getAddress(), serverAttr);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
//		// 加载公网服务器
//		ServerAttr attr = new ServerAttr().setName("默认主服务").setHost("113.98.201.156").setPort(8023).setType(1)
//				.setStatus(ServerAttr.status_1).setAddress("11111111111111111111111111111111");
//		add(attr.getAddress(), attr);
		return init;
	}

	@Override
	public boolean add(String key, ServerAttr value) {

		if (value.getType() == ServerAttr.type_1) {
			ServerAttr select = new ServerAttr();
			if (value.getId() != null) {
				select.setId(value.getId());
			} else {
				select.setAddress(value.getAddress());
			}
			select = dao.select(select);
			if (select != null) {
				select.InitBean(value.toJson());
				dao.updata(select);
			} else {
				select = dao.save(value);
				value = select;
			}
			select.setStatus(ServerAttr.status_1);
		}
		ServerAttr serverAttr = get(key);
		boolean is_new = false;
		if (serverAttr == null) {
			is_new = true;
			super.add(key, value);
		} else {
			if (serverAttr != value)
				serverAttr.InitBean(value.toJson());
		}
		switch (value.getStatus()) {
		case ServerAttr.status_1:// 交给待连接的处理线程。
			WaitConnectionTask.add(key);
			break;
		case ServerAttr.status_3:// 已连接
			if (is_new)
				perHandleTask.add(key);
			break;
		default:
			break;
		}
		return true;
	}

	@Autowired
	private PerHandleTask perHandleTask;

	@Override
	public ServerAttr del(String key) {
		udpServerManager.del(key);
		ServerAttr select = dao.select(new ServerAttr().setAddress(key));
		if (select != null)
			dao.remove(select);
		return super.del(key);
	}

	/**
	 * 得到所有的公网服务器json串
	 *
	 * @return
	 * @author 木鬼
	 */
	public String getPublicServerString() {
		JSONArray array = new JSONArray();
		Iterator<Entry<String, ServerAttr>> iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, ServerAttr> next = iterator.next();
			if (next.getValue().getType() == ServerAttr.type_1 && next.getValue().getStatus() == ServerAttr.status_3)
				array.add(next.getValue().toJson());
		}
		return array.toString();
	}
}
